/*
 * @Author: HuRrongChao 1556810922@qq.com
 * @Date: 2024-04-17 20:07:46
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-04-18 20:55:43
 */
const moment = require('moment')
const express = require('express')
const router = express.Router()
// commontJs, ES6 module
const uploadFile = require('./upload/uploadFile.js')
//jwt
const jwt = require('jsonwebtoken')
const config = require('./jwt/config.js')
const { pool, data_url } = require('./database.js');
const { getVideoList, recordHistory, getComment, addComment, addDanmaku, shareVideo, toggleLike, toggleCollection, getLikeStatus, getCollectionStatus, searchVideos, getUserVideos } = require('./interfaces/api_video.js');
const { getFriends, getMessages, sendMessage, deleteFriendship, followUser, searchUsers } = require('./interfaces/api_chat.js');
const { getConfessionBarrages, sendConfessionBarrage } = require('./interfaces/api_Confession.js');
const {
  getForumPosts,
  createPost,
  getPostComments,
  createComment,
  togglePostLike
} = require('./interfaces/api_forum.js');

// 搜索视频
router.post('/searchVideos', searchVideos);

// 获取指定用户发布的视频列表
router.post('/getUserVideos', getUserVideos); 

// 配置get方法接口,返回推荐视频列表
router.get('/getVideoList', getVideoList);

// 记录观看历史
router.post('/recordHistory', recordHistory);

// 配置get方法接口,返回评论
router.get('/getComment/:videoID', getComment);

// 插入评论接口
router.post('/addComment', addComment);

// 插入弹幕接口
router.post('/addDanmaku', addDanmaku);

// 分享视频
router.post('/shareVideo', shareVideo)

// 点赞/取消点赞
router.post('/toggleLike', toggleLike);

// 收藏/取消收藏
router.post('/toggleCollection', toggleCollection);

// 获取点赞状态
router.post('/getLikeStatus', getLikeStatus);

// 获取收藏状态
router.post('/getCollectionStatus', getCollectionStatus);

// 配置get方法接口,判断当前是否为登陆状态
router.get('/isLogin', async (request, response) => {
  try {
    const token = request.headers['authorization']
    
    if (!token) {
      return response.json({
        msg: '未登录',
        code: "401",
        type: 'notLogin'
      });
    }

    // 验证token
    const decoded = jwt.verify(token, config.jwtSecretKey);
    const account = decoded.account;

    // 查询用户信息
    const sql = 'SELECT user_id, author_name, avatar_url FROM users WHERE user_account = ?';
    const [results] = await pool.execute(sql, [account]);

    if (results.length === 0) {
      return response.json({
        msg: '用户不存在',
        code: "404",
        type: 'userNotFound'
      });
    }

    response.json({
      msg: 'success',
      code: "200",
      type: 'isLogin',
      data: {
        user_id: results[0].user_id,
        author_name: results[0].author_name,
        avatar_url: results[0].avatar_url ? data_url + results[0].avatar_url : null
      }
    });
  } catch (error) {
    if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
      return response.json({
        msg: '登录已过期',
        code: "401",
        type: 'tokenExpired'
      });
    }
    
    console.error('验证登录状态失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      type: 'serverError'
    });
  }
});

// 获取新的token
router.post('/refreshToken', (request, response) => {
  const token = request.body.token
  // 返回解码的有效负载，而不验证签名是否有效。
  const account = jwt.decode(token).account
  const times = jwt.decode(token).times
  jwt.verify(token, config.jwtSecretKey, (err, data) => {
    if (err && err.message === 'invalid token') {
      response.json({
        message: '无效 token',
        code: 0,
        type: 'Ineffective_token'
      })
    }
    else if (err && err.message === 'jwt expired') {
      if (times <= 1) {
        const REFRESH_TOKEN = jwt.sign({ account, times: 2 }, config.jwtSecretKey, { expiresIn: config.expiresIn })
        response.json({
          msg: 'success',
          code: "200",
          token: REFRESH_TOKEN
        })
      }
      else response.json({
        msg: '请重新登录!',
        code: 0,
        type: 'loginAgain'
      })
    }
    else response.json({
      msg: '未知错误',
      code: "500"
    })
  })
})

// 验证登录接口，post方法接口
router.post('/login', async (request, response) => {
  // 查询用户信息
  const sql = 'SELECT user_id, user_account, user_password, author_name, avatar_url FROM users WHERE user_account = ?'
  try {
    const account = request.body.account
    const [results, fields] = await pool.execute(sql, [account])
    if (results[0].user_password === request.body.password) {
      const token = jwt.sign({ account, times: 1 }, config.jwtSecretKey, { expiresIn: config.expiresIn })
      response.json({
        msg: 'success',
        code: "200",
        token,
        data: {
          user_id: results[0].user_id,
          author_name: results[0].author_name,
          avatar_url: data_url + results[0].avatar_url
        }
      })
    } else {
      response.json({
        msg: '账号密码错误，请重试！',
        code: "401"
      })
    }
  } catch (error) {
    console.log(error)
    response.json({
      msg: '服务器错误！请联系管理员!',
      code: "500"
    })
  }
})

// 注册接口
router.post('/register', async (request, response) => {
  try {
    const { account, password, email } = request.body;

    // 1. 检查用户名是否已存在
    const checkUserSql = 'SELECT user_id FROM users WHERE user_account = ?';
    const [existingUsers] = await pool.execute(checkUserSql, [account]);

    if (existingUsers.length > 0) {
      return response.json({
        msg: '该账号已被注册',
        code: "400"
      });
    }

    // 2. 插入新用户
    const insertUserSql = `
      INSERT INTO users 
      (user_account, user_password, author_name, avatar_url, user_email)
      VALUES (?, ?, ?, ?, ?)
    `;

    const defaultAvatar = '/avatar/default.jpg'; // 默认头像路径
    const [result] = await pool.execute(insertUserSql, [
      account,
      password,
      account, // 默认昵称与账号相同
      defaultAvatar,
      email
    ]);

    if (result.affectedRows === 1) {
      response.json({
        msg: '注册成功',
        code: "200",
        data: {
          user_id: result.insertId,
          user_account: account,
          author_name: account,
          avatar_url: data_url + defaultAvatar
        }
      });
    } else {
      response.json({
        msg: '注册失败',
        code: "500"
      });
    }

  } catch (error) {
    console.error('注册失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      error: error.message
    });
  }
});

// 文件上传接口--用于接收视频封面并更新视频信息
router.post('/uploadFile', uploadFile, async (request, response) => {
  try {
    const { video_title, video_type, video_duration, video_size, status } = request.body;
    const author_id = request.query.user_id
    const school_code = request.query.school_code || 0; // 获取当前学校代码，默认为0
    
    // 构建更新SQL
    const updateSql = `
      UPDATE video_list 
      SET 
        video_title = ?,
        video_type = ?,
        video_duration = ?,
        video_size = ?,
        status = ?,
        cover_url = ?,
        school_code = ?
      WHERE author_id = ?
      ORDER BY video_date DESC 
      LIMIT 1
    `;

    // 执行更新
    const [result] = await pool.execute(updateSql, [
      video_title,
      video_type,
      video_duration,
      video_size,
      status || 1,  // 默认状态为1（已发布）
      `/thumb_list/${request.file.filename}`,
      school_code,
      author_id
    ]);

    if (result.affectedRows === 0) {
      return response.send({
        type: 'error',
        code: 0,
        message: '未找到对应的视频记录',
        data: null
      });
    }

    response.send({
      type: 'success',
      code: 1,
      message: '封面上传成功并更新了视频信息',
      url: request.file ? `${data_url}/${request.file.filename}` : '',
      school_code: school_code
    });

  } catch (error) {
    console.error('更新视频信息失败:', error);
    response.send({
      type: 'error',
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
});

// 创建 Socket.IO 服务器
const initSocketServer = (io) => {
  // 用户映射表
  const userSocketMap = new Map();

  io.on('connection', (socket) => {
    const userId = socket.handshake.query.user_id;
    const username = socket.handshake.query.author_name;

    console.log(`用户连接: ${username}(${userId})`);
    
    // 保存用户socket映射
    userSocketMap.set(userId, socket);

    // 处理私聊消息
    socket.on('friendMessage', async (message) => {
      try {
        // 保存消息到数据库
        const sql = `
          INSERT INTO chat_messages 
          (sender_id, receiver_id, content, send_time) 
          VALUES (?, ?, ?, NOW())
        `;
        await pool.execute(sql, [
          message.userId,
          message.receiverId,
          message.content
        ]);

        // 获取发送者信息
        const userSql = `
          SELECT user_id, author_name, avatar_url 
          FROM users 
          WHERE user_id = ?
        `;
        const [userInfo] = await pool.execute(userSql, [message.userId]);

        // 构建完整的消息对象
        const fullMessage = {
          ...message,
          sendTime: new Date(),
          senderInfo: {
            userId: userInfo[0].user_id,
            username: userInfo[0].author_name,
            avatar: userInfo[0].avatar_url ? data_url + userInfo[0].avatar_url : null
          }
        };

        // 如果接收者在线，发送消息
        const receiverSocket = userSocketMap.get(message.receiverId + '');
        if (receiverSocket) {
          receiverSocket.emit('newMessage', fullMessage);
        }

        // 同时发送给发送者，用于确认消息已发送
        socket.emit('messageSent', fullMessage);
      } catch (error) {
        console.error('保存消息失败:', error);
        socket.emit('messageError', {
          error: '发送消息失败',
          message: error.message
        });
      }
    });

    // 断开连接时清理
    socket.on('disconnect', () => {
      console.log(`用户断开: ${username}(${userId})`);
      userSocketMap.delete(userId);
    });
  });
};

// 获取好友列表
router.get('/friends', getFriends);

// 获取聊天记录
router.get('/messages', getMessages);

// 发送消息接口
router.post('/sendMessage', sendMessage);

// 删除好友关系
router.post('/deleteFriendship', deleteFriendship);

// 关注用户
router.post('/followUser', followUser);

// 搜索用户
router.post('/searchUsers', searchUsers);

// 获取表白墙弹幕列表
router.get('/getConfessionBarrages', getConfessionBarrages);

// 发送表白墙弹幕
router.post('/sendConfessionBarrage', sendConfessionBarrage);

// 获取帖子列表
router.post('/getForumPosts', getForumPosts);

// 发布帖子
router.post('/createPost', createPost); 

// 获取帖子评论
router.post('/getPostComments', getPostComments);

// 发表评论
router.post('/createComment', createComment);

// 点赞/取消点赞帖子
router.post('/togglePostLike', togglePostLike);


module.exports = {
  pool,
  data_url,
  router,
  initSocketServer
}